package q478_randPoint;

import java.util.Random;

public class Solution {
    double radius;
    double x_center;
    double y_center;
    public Solution(double radius, double x_center, double y_center) {
        this.radius = radius;
        this.x_center = x_center;
        this.y_center = y_center;
    }

    /*
    想法1：
    在圆心为原点，半径为1的圆中生成一个点 然后等比例放大坐标，并且偏移到对应的圆内
    但是无法通过所有测试用例
     */
    public double[] randPoint_1() {
        double boarder_0 = 0.0d, boarder_1 = 1.0d;
        double generate_x = boarder_0 + Math.random() * boarder_1 % (boarder_1 - boarder_0 + 1);

        double half = Math.sqrt(1.0d - generate_x * generate_x);
        double generate_y = -half + Math.random() * half % (half + half + 1);

        generate_x *= radius;
        generate_y *= radius;
        generate_x += x_center;
        generate_y += y_center;
        return new double[]{generate_x, generate_y};
    }

    /*
    想法2：
    在对应的正方形区域随机产生一个点
    如果该点在圆的范围内，则返回
    效率较低
     */
    public double[] randPoint_2() {
        while (true) {
            double generate_x = x_center - radius + Math.random() * 2 * radius;
            double generate_y = y_center - radius + Math.random() * 2 * radius;
            if ((generate_x - x_center) * (generate_x - x_center) + (generate_y - y_center) * (generate_y - y_center) <= radius * radius) return new double[]{generate_x, generate_y};
        }
    }

    /*
    想法3：
    最优解
    计算分布函数
    用 r = sqrt(u) 来生成随机变量 r 才真正符合在圆的范围内随机生成
     */
    public double[] randPoint() {
        Random random = new Random();
        double u = random.nextDouble();
        double theta = random.nextDouble() * 2 * Math.PI;
        double r = Math.sqrt(u);
        return new double[]{x_center + r * Math.cos(theta) * this.radius, y_center + r * Math.sin(theta) * this.radius};
    }

}
